﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NapCardOnline.Models;
using MvcLibrary;
using MvcUtil;
using PagedList;
using MvcBase;


namespace NapCardOnline.Controllers
{
    public class TransferFundController : MyMvcController
    {
        private NapCardOnlineEntities db = new NapCardOnlineEntities();
    
        public ActionResult Index(int? page)
        {
            User objUser = Session["User"] as User;
            var transferFunds =
                db.TransferFunds.Include("TransferFundType").Include("User").Include("Status").Where(t => t.FK_ToUserID == objUser.UserID || t.FK_FromUserID == objUser.UserID).
                    OrderByDescending(t => t.TransferFundDate);
            foreach (var item in transferFunds)
            {
                item.Amount = string.Format("{0:0,0}", item.TransferFundAmount);
                item.CommisionAmount = string.Format("{0:0,0}", item.TransferFundCommissionAmount);
            }
            var pageNumber = page ?? 1;
            var onePageOfTransferFund = transferFunds.ToPagedList(pageNumber, 10);
            ViewBag.OnePageOfTransferFund = onePageOfTransferFund;
            
            ViewBag.CountTransfer = transferFunds.Count();
            ViewBag.TotalAmount = string.Format("{0:0,0}", transferFunds.Sum(t => t.TransferFundAmount));
            ViewBag.TotalCommisionAmount = string.Format("{0:0,0}", transferFunds.Sum(t => t.TransferFundCommissionAmount));
            return View(onePageOfTransferFund);
        }
        //
        // GET: /TransferFund/Create
        public ActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// Checks the user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns>Check user about exist and level</returns>
        public JsonResult CheckUser(string userName,string amount)
        {
            var objUSerFrom = Session["User"] as User;
            using (var db = new NapCardOnlineEntities())
            {
                var objUserTo = db.Users.FirstOrDefault(u => u.UserName == userName);
                if (objUserTo != null && objUSerFrom != null)
                {
                    if(Convert.ToDouble(amount)<=0)
                    {
                        return Json(new
                                        {
                                           ischeck=false,
                                           name = "balance",
                                           success="Số tiền phải lớn hơn 0.",
                                        });
                    }
                    #region Check User Duplicate
                    if (objUSerFrom.UserName == userName)
                    {
                        return Json(new
                                        {
                                            ischeck = false,
                                            name = "touser",
                                            success = "Tài khoản chuyển tiền và tài khoản nhận tiền không được trùng nhau.",
                                        });
                    }
                    Json(new { ischeck = true });

                    #endregion

                    #region Check user level
                    if (Models.User.CheckUserLevel(objUSerFrom.UserLevel, objUserTo.UserLevel))
                    {
                         Json(new { ischeck = true });
                    }
                    else
                    {
                        return Json(new
                        {
                            ischeck = false,
                            name = "transfer",
                            success = "Level của người chuyển tiền phải lớn hơn người nhận."
                        });
                    }

                    #endregion

                    #region Check Balance
                    if (Models.User.CheckUserBlance(objUSerFrom.UserBalance,Convert.ToDouble(amount.Trim())))
                    {
                        return Json(new { ischeck = true });
                    }
                    else
                    {
                        return Json(new
                        {
                            ischeck = false,
                            name = "balance",
                            success = "Số dư của bạn không đủ để thực hiện giao dịch."
                        });
                    }
                    #endregion
                }
                else
                {
                    return Json(new
                    {
                        ischeck = false,
                        name = "touser",
                        success = "Tài khoản người nhận tiền không tồn tại."
                    });
                }
            }
        }

        //
        // POST: /TransferFund/Create
        [HttpPost]
        public ActionResult Create(TransferFund transferfund)
        {
            if (ModelState.IsValid)
            {
                var objUserFrom = Session["User"] as Models.User;
                var objUserTo = db.Users.FirstOrDefault(u => u.UserName == transferfund.ToUser);
                if (objUserTo != null && objUserFrom != null)
                {
                    //Check user 
                    if (!objUserFrom.UserID.Equals(objUserTo.UserID))
                    {
                        if (objUserFrom.UserBalance >= transferfund.TransferFundAmount)
                        {
                            var objTransferFund = new TransferFund();
                            try
                            {
                                using (var transaction = MvcBase.BaseTransaction.BeginTransaction(db))
                                {
                                    objTransferFund.FK_FromUserID = objUserFrom.UserID;
                                    objTransferFund.FK_ToUserID = objUserTo.UserID;
                                    objTransferFund.TransferFundNo = MvcUtil.ObjectUtil.GenerateNumber("TransferFund",
                                                                                                       db.TransferFunds,
                                                                                                       t =>
                                                                                                       t.TransferFundID);
                                    // Tính chiết khấu
                                    objTransferFund.CommisionPercent =
                                        Models.User.GetCommisionPercent(objUserFrom.UserID, objUserTo.UserID);
                                    //objTransferFund.CurrentBalance = objUserFrom.UserBalance;
                                    objTransferFund.TransferFundAmount = transferfund.TransferFundAmount;
                                    objTransferFund.TransferFundCommissionAmount = transferfund.TransferFundAmount *
                                                                                   objTransferFund.CommisionPercent / 100;
                                    objTransferFund.TransferFundDate = DateTime.Now;
                                    objTransferFund.TransferFundDesc = transferfund.TransferFundDesc;
                                    if (Models.User.CheckUserLevel(objUserFrom.UserLevel, objUserTo.UserLevel))
                                    {
                                        objTransferFund.FK_TransferFundTypeID =
                                            TransferFundType.GetTransferFundTypeByUserLevel(objUserFrom.UserLevel,
                                                                                            objUserTo.UserLevel);
                                        objTransferFund.FK_StatusID = (int)Enum.Status.Success;
                                        db.TransferFunds.AddObject(objTransferFund);
                                        db.SaveChanges();

                                        //Cập nhật số dư và ngày edit cho từng user
                                        if (Models.User.UpdateBalanceWhenTransferFund(objTransferFund))
                                        {
                                            transaction.Commit();
                                            if (Request.IsAjaxRequest())
                                            {
                                                return Json(new
                                                {
                                                    info = "Chuyển tiền thành công!",
                                                    redirectToUrl = Url.Action("Index"),
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    //else
                    //TODO: Thong bao cho khach hang biet trung user nen ko chuyen tien
                }
                //else
                //TODO: Thong bao user ko ton tai
            }
            return View(transferfund);
        }

        //Action result for ajax call for autosuggest
        public JsonResult GetAutosuggestByUserName(string term)
        {
            var objstate = db.Users.Where(m => m.UserName.Contains(term)).Select(m => new { m.UserID, value = m.UserName }).ToList();
            return Json(objstate.ToArray(), JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);

        }
    }
}